package com.haitonghop.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class PhotoUtils 
{
	
	public static boolean isValidImage(File file){
		try {
			final int BUFFER_SIZE = 1024;
			
			FileInputStream fileInputStream = new FileInputStream(file);			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[BUFFER_SIZE]; // Experiment with this value
			int bytesRead;
			while ((bytesRead = fileInputStream.read(buffer)) != -1)
			{
				baos.write(buffer, 0, bytesRead);
			}		
			fileInputStream.close();	
			
			return isValidImage(baos.toByteArray());
			
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return false;
	}
	
	public static boolean isValidImage(byte[] data){
		if(isPNG(data))
			return true;
		else {
			if(isValidJPEG(data))
				return true;
		}
		return false;
	}

	public static boolean isPNG(byte[] data){
		if (data == null || data.length < 8)
			return false;

		if( data[0] == (byte) 0x89
				&& 	data[1] == (byte) 0x50
				&& 	data[2] == (byte) 0x4E
				&& 	data[3] == (byte) 0x47
				&& 	data[4] == (byte) 0x0D
				&& 	data[5] == (byte) 0x0A
				&& 	data[6] == (byte) 0x1A
				&& 	data[7] == (byte) 0x0A
				)
			return true;
		return false;
	}

	public static boolean isValidJPEG(byte[] data) {
		if (data == null || data.length < 2)
			return false;

		int totalBytes = data.length;

		return (data[0] == (byte) 0xff && data[1] == (byte) 0xd8
				&& data[totalBytes - 2] == (byte) 0xff && data[totalBytes - 1] == (byte) 0xd9);
	}

}
